<template>
  <div class="container">
    <el-row class="top-row">
      <el-col :span="3" class="search-container">
        <el-input v-model="keyword" placeholder="模糊查询" size="small" />
      </el-col>
      <el-col :span="1">
        <el-button
          v-show="permission.hasAdd"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="openInsertForm"
        >
          新增
        </el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="23">
        <el-table
          v-loading="isLoad"
          class="table-row"
          size="mini"
          :data="roles"
        >
          <el-table-column label="角色名称" align="center" prop="rolename" />
          <el-table-column label="角色描述" align="center" prop="remark" />
          <el-table-column label="角色类别" align="center">
            <template slot-scope="{ row }">
              <template v-if="row.roletype === 1"> 本系统通用角色 </template>
              <template v-else-if="row.roletype === 2"> 一键发布角色 </template>
            </template>
          </el-table-column>

          <el-table-column align="left" label="操作" width="300px">
            <template slot-scope="{ row }">
              <el-button
                v-show="permission.hasUpdate"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="openUpdateForm(row)"
              >
                修改
              </el-button>
              <el-button
                v-show="permission.hasDelete"
                icon="el-icon-delete"
                type="danger"
                size="mini"
                @click="deleteRow(row)"
              >
                删除
              </el-button>

              <el-dropdown :hide-on-click="false">
                <el-button size="mini" type="info" style="margin-left: 10px">
                  更多 >
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    v-if="row.roletype !== 2"
                    @click.native="openMallocWindow(row)"
                  >
                    分配角色
                  </el-dropdown-item>
                  <el-dropdown-item
                    v-show="permission.hasMalloc"
                    @click.native="openPermManageWindow(row)"
                  >
                    分配权限
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <el-row class="top-row">
      <el-col :span="20">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="size"
          :current-page.sync="page"
        />
      </el-col>

      <el-col :span="2" class="page-size-container">
        <el-select v-model="size" placeholder="页大小" size="small">
          <el-option
            v-for="(item, index) in sizeList"
            :key="index"
            :label="item + '条/页'"
            :value="item"
          />
        </el-select>
      </el-col>
      <el-col :span="2" class="page-total-container">
        总 {{ total }} 条
      </el-col>
    </el-row>

    <el-dialog
      title="📝修改"
      :visible.sync="edit.show"
      width="40%"
      :before-close="formClose"
    >
      <role-form
        ref="updateForm"
        :data="edit.target"
        @submit="updateFormSubmit"
      />

      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="edit.show = false"> 取 消 </el-button>
        <el-button type="primary" size="medium" @click="checkUpdateForm">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="📝修改"
      :visible.sync="addit.show"
      width="40%"
      :before-close="formClose"
    >
      <role-form
        ref="insertForm"
        :data="addit.target"
        @submit="insertFormSubmit"
      />

      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="addit.show = false"> 取 消 </el-button>
        <el-button type="primary" size="medium" @click="checkInsertForm">
          确 定
        </el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="🎨分配角色"
      :visible.sync="malloc.show"
      width="45%"
      :before-close="formClose"
    >
      <el-row>
        <el-col :span="11">
          <el-table
            v-loading="malloc.nousersLoad"
            :data="malloc.nousers"
            :show-header="false"
            max-height="500px"
            class="user-list"
          >
            <el-table-column prop="username" />
            <el-table-column width="100px">
              <template slot-scope="{ row }">
                <el-button plain size="mini" @click="addUserToRoleGroup(row)">
                  添加
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>

        <el-col :span="11" :offset="1">
          <el-table
            v-loading="malloc.usersLoad"
            :data="malloc.users"
            :show-header="false"
            max-height="500px"
            class="user-list"
          >
            <el-table-column prop="username" />
            <el-table-column width="100px">
              <template slot-scope="{ row }">
                <el-button
                  type="danger"
                  plain
                  size="mini"
                  @click="removeUserToRoleGroup(row)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer" />
    </el-dialog>

    <el-dialog
      top="5%"
      title="🎨分配权限"
      :visible.sync="permManage.show"
      width="65%"
      :before-close="formClose"
    >
      <perm-manage :data="permManage.target" />

      <span slot="footer" class="dialog-footer" />
    </el-dialog>
  </div>
</template>

<script>
import { HTTP_OK } from "@/api/constants";
import {
  getRolesData,
  getNouserByRole,
  getUserByRole,
  updateRole,
  insertRole,
  deleteRole,
  addRoleFromUser,
  removeRoleFromUser,
} from "@/api/system-manage/role";
import RoleForm from "./RoleForm.vue";
import PermManage from "./PermManage/";
import { OperationType, recordOperateLogFunc } from "@/api/log";
import { hasRolePermission } from "./perm";

const recordOperateLog = recordOperateLogFunc("系统管理", "角色管理");

export default {
  components: { RoleForm, PermManage },
  data() {
    return {
      // 用户数据
      roles: [],
      // 是否处于加载
      isLoad: true,
      // 总数
      total: 0,
      // 页数
      page: 1,
      // 每页大小
      size: 15,
      // 搜索关键词
      keyword: "",
      // 每页大小候选项
      sizeList: [10, 15, 20, 30, 40, 50],

      // 防抖计时器
      keywordTimer: setTimeout(() => {}, 555),

      // 修改窗口状态
      edit: {
        // 显示
        show: false,
        // 修改的目标数据
        target: {},
      },

      // 新增窗口状态
      addit: {
        // 显示
        show: false,
        // 修改的目标数据
        target: {},
      },

      // 分配角色窗口状态
      malloc: {
        show: false,
        // 打开的目标角色
        target: {},
        // 未分配所选角色的用户列表
        nousers: [],
        // 已分配所选角色的用户列表
        users: [],
        // 未分配所选角色的用户列表是否处于加载状态
        nousersLoad: true,
        // 已分配所选角色的用户列表是否处于加载状态
        usersLoad: true,
      },

      // 权限管理
      permManage: {
        show: false,
        target: {},
      },

      permission: {
        hasAdd: false,
        hasUpdate: false,
        hasDelete: false,
        hasSelect: false,
        hasMalloc: false,
      },
    };
  },

  watch: {
    page() {
      this.refreshRoleList();
    },
    size() {
      this.refreshRoleList();
    },
    keyword() {
      this.$data.isLoad = true;
      // 置为页数1
      this.$data.page = 1;
      // 计时器防抖
      clearTimeout(this.$data.keywordTimer);
      this.$data.keywordTimer = setTimeout(this.refreshRoleList, 555);
    },
  },
  mounted() {
    this.$data.permission = hasRolePermission();
    this.refreshRoleList();
  },

  methods: {
    /**
     * 刷新列表
     */
    async refreshRoleList() {
      if (this.$data.permission.hasSelect === false) {
        this.$message.warning("没有该页面的查询权限");
        return;
      }
      this.$data.isLoad = true;
      const { page, size, keyword } = this.$data;
      const { results, count } = await getRolesData(page, size, keyword);
      this.$data.roles = results;
      this.$data.total = count;
      this.$data.isLoad = false;
      recordOperateLog(OperationType.Select);
    },

    /**
      刷新打开的分配角色的用户列表
    */
    async refreshRowRoleUserList() {
      const { id: rid } = this.$data.malloc.target;

      this.$data.malloc.nousersLoad = true;
      this.$data.malloc.usersLoad = true;
      // 不写await 因为串行请求效率太低
      getNouserByRole(rid).then(({ status, detail }) => {
        if (status === HTTP_OK) {
          this.$data.malloc.nousers = detail;
        } else {
          this.$message.error(detail);
        }
        this.$data.malloc.nousersLoad = false;
      });

      const { status, detail } = await getUserByRole(rid);
      if (status === HTTP_OK) {
        this.$data.malloc.users = detail;
      } else {
        this.$message.error(detail);
      }
      this.$data.malloc.usersLoad = false;
    },

    formClose(done) {
      this.$confirm("确认关闭？").then(() => {
        done();
      });
    },

    openUpdateForm(row) {
      // 拷贝，避免直接修改引用
      this.$data.edit.target = JSON.parse(JSON.stringify(row));
      this.$data.edit.show = true;
    },

    /*
     * 检查表单
     * 通过检查后会触发updateFormSubmit
     */
    checkUpdateForm() {
      this.$refs.updateForm.submit();
    },

    /**
     * 提交修改表单
     */
    async updateFormSubmit() {
      const form = this.$refs.updateForm.data;
      const { status, detail } = await updateRole(form);
      if (status === HTTP_OK) {
        recordOperateLog(OperationType.Update);
        this.$message.success(detail);
        this.$data.edit.show = false;
        this.refreshRoleList();
      } else {
        this.$message.error(detail);
      }
    },

    openInsertForm() {
      this.$data.addit.target = {
        rolename: "",
        remark: "",
        roletype: 1,
      };

      this.$data.addit.show = true;
    },

    /**
     * 检查新增表单
     */
    checkInsertForm() {
      this.$refs.insertForm.submit();
    },

    async insertFormSubmit() {
      const form = this.$refs.insertForm.data;
      const { status, detail } = await insertRole(form);
      if (status === HTTP_OK) {
        recordOperateLog(OperationType.Add);
        this.$message.success("创建成功");
        this.$data.addit.show = false;
        this.refreshRoleList();
      } else {
        this.$message.error("错误:" + detail);
      }
    },

    /**
     * 删除该行
     * @param {*} row
     */
    deleteRow(row) {
      this.$confirm(`确认要删除${row.rolename}这个角色?`, "提示", {
        type: "warning",
      }).then(async () => {
        const { status, detail } = await deleteRole(row.id);
        if (status === HTTP_OK) {
          recordOperateLog(OperationType.Delete);
          this.$message.success(detail);
          this.refreshRoleList();
        } else {
          this.$message.error(detail);
        }
      });
    },

    /**
     * 打开分配规则窗口
     * @param {*} row
     */
    openMallocWindow(row) {
      this.$data.malloc.target = row;
      this.$data.malloc.show = true;

      this.refreshRowRoleUserList();
    },

    async addUserToRoleGroup(user) {
      const { id: uid } = user;
      const { id: rid } = this.$data.malloc.target;
      const { status, detail } = await addRoleFromUser(uid, rid);
      recordOperateLog(OperationType.MallocUser);
      if (status === HTTP_OK) {
        this.refreshRowRoleUserList();
      } else {
        this.$message.error(detail);
      }
    },
    async removeUserToRoleGroup(user) {
      const { id: uid } = user;
      const { id: rid } = this.$data.malloc.target;
      const { status, detail } = await removeRoleFromUser(uid, rid);
      recordOperateLog(OperationType.MallocUser);
      if (status === HTTP_OK) {
        this.refreshRowRoleUserList();
      } else {
        this.$message.error(detail);
      }
    },

    openPermManageWindow(row) {
      this.$data.permManage.target = row;
      this.$data.permManage.show = true;
    },
  },
};
</script>

<style>
.container {
  padding-left: 20px;
}

/* 顶行 */
.top-row {
  margin-top: 15px;
}
/* 搜索外部DIV容器 */
.search-container {
  padding-right: 10px;
}

/* 表格行 */
.table-row {
  margin-top: 10px;
}

.table-header {
  background-color: #ddd;
}

/* 角色标签 */
.role-tag {
  margin-right: 5px;
  margin-top: 5px;
}

/* 页数选择外部DIV */
.page-size-container {
  padding-right: 15px;
}

/* 显示总页数外部div*/
.page-total-container {
  padding-top: 7px;
  font-size: 14px;
}

.user-list {
  border: #ebeef5 1px solid;
}

/* 追加eui的对话框样式 */
.el-dialog .el-dialog__body {
  padding-bottom: 0px;
}

*::-webkit-scrollbar {
  width: 7px;
  height: 10px;
  background-color: transparent;
} /*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/
*::-webkit-scrollbar-track {
  background-color: #f0f6ff;
} /*定义滚动条轨道 内阴影+圆角*/
*::-webkit-scrollbar-thumb {
  background-color: #409eff;
  border-radius: 2px;
} /*定义滑块 内阴影+圆角*/
.scrollbarHide::-webkit-scrollbar {
  display: none;
}
.scrollbarShow::-webkit-scrollbar {
  display: block;
}
</style>
